import { camelCase, upperFirst, transform, last, isArray } from 'lodash';
export * from './define';

function getCase(k, t) {
  return (
    (t === 'lowerCase' ? k[0].toLowerCase() : k[0].toUpperCase()) +
    k.substring(1)
  );
}
function getLowerCase(k) {
  return getCase(k, 'lowerCase');
}
function getUpperCase(k) {
  return getCase(k);
}

export function adaptUMD(key, value) {
  let uuid = '__teld__312657d3-cf6f-4586-9854-5082817ab4b2';
  let k = uuid + key;
  if (!window[k]) {
    window[k] = value;
  }
  return window[k];
}

export const commonProps = {
  visible: {
    type: Boolean,
    default() {
      return true;
    },
  },
};

export function pickOwnForBasicComponent(props, basicProps, attrs) {
  let o = {};
  let a = Object.entries(basicProps ?? {});
  a.forEach(([k, v], i, a) => {
    if ((k == 'props' || k == 'Props') && props[k]) return;
    o[k] = props[k];
  });
  a = Object.entries(attrs ?? {});
  a.forEach(([k, v], i, a) => {
    if (/update:/i.test(k)) {
      o[k] = v;
    }
  });

  return o;
}

export function createNameSpace(name = '', prefixed = 'T') {
  if (!name) {
    throw new Error('name 为必填项');
  }
  return upperFirst(prefixed) + upperFirst(camelCase(name));
}

export function fixNameSpace(name = '') {
  let r = /^Q/;
  if (r.test(name)) {
    return name.replace(r, 'T');
  } else {
    return createNameSpace(name);
  }
}


export function zipFasDynamicFilter(o, Filters) {
  if (!Filters) {
    return {};
  }
  let filter = typeof Filters == 'string' ? JSON.parse(Filters) : Filters;
  if (false == isArray(filter)) {
    filter = [filter];
  }
  transform(
    filter,
    (r, v) => {
      if (v.ElementType == 'Filter') {
        r[last(v.Code.split('.'))] = v.Value;
      } else if (v.ElementType == 'Group') {
        zipFasDynamicFilter(o, v.Filters);
      }
    },
    o,
  );
  return o;
}

export const SymbolDestructuring = Symbol('SymbolDestructuring');

export function isValueDestructuring(val) {
  return val?.[SymbolDestructuring];
}

export function valueDestructuring(val) {
  let value = val?.value || val;
  let label = val?.label || val;

  if (isValueDestructuring(val)) {
    value = val.valueOf();
    label = val[SymbolDestructuring] || value;
  }
  return { value, label };
}

export function valueStructuring(val) {
  let returnValue = new Object(val.Value);
  if (['true', 'false'].includes(val.Value)) {
    returnValue = new Object('true' === val.Value);
  }
  returnValue[SymbolDestructuring] = val.ValueName;
  return returnValue;
}

export function filter2FasDynamicFilter(o, Filters, destructuring = false) {
  if (!Filters) {
    return {};
  }
  let filter = typeof Filters == 'string' ? JSON.parse(Filters) : Filters;
  if (false == isArray(filter)) {
    filter = [filter];
  }
  transform(
    filter,
    (r, v) => {
      if (v.ElementType == 'Filter') {
        r[v.Code] = v.Value;
        if (destructuring) {
          r[v.Code] = valueStructuring(v);
        }
      } else if (v.ElementType == 'Group') {
        filter2FasDynamicFilter(o, v.Filters, destructuring);
      }
    },
    o,
  );
  return o;
}
export function mergeFiltersBase(target = {}, ...sArgs) {
  if (typeof target === 'string') {
    try {
      target = JSON.parse(target);
    } catch (error) {
      console.warn('QuickFilter.getQuickFilter', error);
    }
  }

  let {
    Filters: tFilters = [],
    ExtSetting: tExtSetting = { GroupColumns: [] },
    ...tQuickFilter
  } = target || {};

  let groupColumns = [...tExtSetting?.GroupColumns];

  _.each(sArgs, sources => {
    if (typeof sources === 'string') {
      try {
        sources = JSON.parse(sources);
      } catch (error) {
        console.warn('QuickFilter.getQuickFilter', error);
      }
    }

    let {
      Filters: sFilters = [],
      ExtSetting: sExtSetting = { GroupColumns: [] },
      ...sQuickFilter
    } = sources || {};

    if (sFilters && sFilters.length > 0) {
      if (tFilters && tFilters.length > 0) {
        tFilters.push({
          ElementType: 'Relation',
          Relation: 'and',
        });
      }
      tFilters.push({
        ...sQuickFilter,
        Filters: sFilters,
      });
    }

    if (sExtSetting?.GroupColumns && sExtSetting?.GroupColumns.length > 0) {
      groupColumns.push(...sExtSetting?.GroupColumns);
    }
  });

  let returnValue = {
    ElementType: 'Group',
    Filters: tFilters,
  };

  if (groupColumns.length > 0) {
    returnValue.ExtSetting = { GroupColumns: groupColumns };
  }
  return returnValue;
}
export function mergeFilters(target = {}, ...sArgs) {
  return JSON.stringify(mergeFiltersBase(target, ...sArgs));
}

// export function fixPropsWithUpperFirst(props = {}) {
//   // 历史原因等，必须做一层首字母大写映射。
//   const a = Object.entries(props ?? {});
//   a.forEach(([k, v], i, a) => {
//     let keyUpperCase = getUpperCase(k);
//     let keyLowerCase = getLowerCase(k);

//     if (!Object.prototype.hasOwnProperty.call(props, keyUpperCase)) {
//       props[keyUpperCase] = null;
//     }
//   });
//   if (Object.prototype.hasOwnProperty.call(props, 'modelValue')) {
//     // props['value'] = props['Value'] = props.modelValue;// 有问题，后面统一处理
//   }
//   return props;
// }
